<template>
  <div class="customer">
    <ListTab v-model="activeId" :show-header="!showMobilePage" :tabs="tabListData" is-table @tabClick="handleTabClick"/>
    <div :class="{'mobile-table mobile-pt mobile-el-pagination mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="filter-input-box">
        <FilterInput
          v-model="filterInput"
          :filter-list="filterList"
          show-search-btn
          class="FilterTool"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <div class="table-top-opeator-bar">
          <el-button v-if="hasRouteAuth('mengli:settleAccountsLog:generate')" :loading="generateLoading" size="small" type="primary" style="margin-right: 10px;" @click="handleGenerate">
            <el-tooltip :open-delay="500" placement="top">
              <div slot="content">最新可生成的内容为上个自然月</div>
              <span>生成</span>
            </el-tooltip>
          </el-button>
          <btnGroup
            v-if="hasRouteAuth('mengli:settleAccountsLog:export')"
            ref="btnGroupRef"
            :list="[
              { label:'导出', exportApi:'/admin/mengli/settleAccountsLog/detail/export', exportName:'结算记录', beforeExport: beforeExport, type: 'export', auth: hasRouteAuth('mengli:settleAccountsLog:export') },
            ]"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          ref="customerTableRef"
          :data="list.items"
          :border="true"
          :row-height="rowHeight()"
          :height="setTableHeight"
          :row-class-name="tableRowClassName"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @selection-change="handleSelectionChange">
          <u-table-column :fixed="showMobilePage?false:'left'" align="center" type="selection" width="50"/>
          <u-table-column align="left" label="结算月份" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.months" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="期初实际数量" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.startCount" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="期初实际金额" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.startAmount" :price="scope.row.startAmount" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="期末实际数量" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.endCount" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="期末实际金额" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.endAmount" :price="scope.row.endAmount" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="仓库" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.repositoryName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.creator" />
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作" >
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <div class="button-text" @click="goDetail(scope.row.id)">查看</div>
                <div v-if="hasRouteAuth('mengli:settleAccountsLog:export')" class="button-text bl" @click="handleSingleExport(scope.row)">导出</div>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item style="width:90px;text-align: center" @click.native="goDetail(scope.row.id)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('mengli:settleAccountsLog:export')" @click.native="handleSingleExport(scope.row)">
                  <div>导出</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="selectedData" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <fixed-pagination>
        <template v-if="showMobilePage">
          <FilterInput
            v-model="filterInput"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <btnGroup
            v-if="hasRouteAuth('mengli:settleAccountsLog:export')"
            ref="btnGroupRef"
            :list="[
              { label:'导出', exportApi:'/admin/mengli/settleAccountsLog/detail/export', exportName:'结算记录', beforeExport: beforeExport, type: 'export', auth: hasRouteAuth('mengli:settleAccountsLog:export') },
            ]"
            style="margin-right: 24px"
          />
          <el-button v-if="hasRouteAuth('mengli:settleAccountsLog:generate')" :loading="generateLoading" size="small" type="primary" style="margin-right: 10px;" @click="handleGenerate">
            <el-tooltip :open-delay="500" placement="top">
              <div slot="content">最新可生成的内容为上个自然月</div>
              <span>生成</span>
            </el-tooltip>
          </el-button>
        </template>
        <template v-else>
          <div class="delete-button-container">
            <SelectionNum :select-item="selectedData" @clearMixinSelection="clearMixinSelection" />
          </div>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import ListTab from '@/components/ListTab';
import { tabListData, handleTabChange, getSkuDiffNumFunc } from './utils';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import TableAdaptive from '@/mixins/tableAdaptive';
import { standardFormatMonth } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { generateSettleAccounts, getInventoryRepo, getSettleAccountsLogList } from '@/api/mengli';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import mobileTable from '@/mixins/mobileTable';

export default {
  filters: {
    standardFormatMonth
  },
  components: {
    ListTab,
    btnGroup,
    EmptyPlaceholder
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      activeId: '3',
      tabListData,
      filterInput: {},
      page: 1,
      perPage: 20,
      selectedData: [],
      exportLoading: false, // 导出按钮loading
      listLoading: false, // 列表loading
      generateLoading: false, // 生成按钮loading
      repositoryOptions: [],
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      totalNum: 0 // 用于比较生成记录
    };
  },
  computed: {
    filterList() {
      const arr = [
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '70px' },
        { keyword: 'repositoryId', name: '选择仓库', type: 'select', options: this.repositoryOptions },
        { keyword: 'months', name: '结算月份', type: 'date', labelWidth: '70px' }
      ];
      return arr;
    }
  },
  created() {
    getSkuDiffNumFunc();
    this.fetchData(true);
    this.getInventoryRepo();
  },
  methods: {
    hasRouteAuth,
    tableRowClassName({ row }) {
      return this.selectedData.some(item => item.id === row.id) ? `table-selected` : '';
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.filterInput));
      params.page = this.page;
      params.perPage = this.perPage;
      this.listLoading = true;
      getSettleAccountsLogList(params).then(res => {
        if (res.code === 200 && res.data) {
          this.list = res.data;
          if (JSON.stringify(this.filterInput) === '{}') {
            this.totalNum = res.data.total;
          }
          this.list.isInit = false;
          this.listLoading = false;
        }
      }, result => {
        this.listLoading = false;
      }).catch(err => {
        console.log(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    mapKey(data) {
      const arr = [];
      data.map(item => {
        const arrItem = {
          value: item.repositoryId,
          label: item.repositoryName
        };
        arr.push(arrItem);
      });
      return arr;
    },
    deleteTagBefore(key) {
      if (key === 'months') {
        this.$set(this.filterInput, 'months', '');
      }
    },
    clearMixinSelection() {
      this.$refs.customerTableRef.clearSelection();
    },
    getInventoryRepo() {
      getInventoryRepo().then(res => {
        this.repositoryOptions = this.mapKey(res.data.items.filter(it => it.type === 1));
      }).catch(err => {
        console.log(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    handleTabClick(id) {
      handleTabChange(id, this);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.filterInput = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    goDetail(id) {
      this.$router.push({
        name: 'mengliSettleAccountsDetail',
        params: {
          id
        }
      });
    },
    handleGenerate() {
      this.generateLoading = true;
      this.listLoading = true;
      this.filterInput = {};
      generateSettleAccounts().then(res => {
        if (res.code === 200 && res.data) {
          this.list = res.data;
          this.list.isInit = false;
          this.listLoading = false;
          this.generateLoading = false;
          if (res.data.total === this.totalNum) {
            this.$message({ type: 'warning', message: '无新结算单可生成' });
          } else {
            this.totalNum = res.data.total;
            this.$message({ type: 'success', message: '生成成功' });
          }
        }
      }, result => {
        this.listLoading = false;
        this.generateLoading = false;
      }).catch(err => {
        console.log(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    beforeExport() {
      if (!this.selectedData.length) {
        this.$message({ type: 'warning', message: '请选择需要导出的表单' });
      } else {
        this.selectedData.map(item => {
          setTimeout(() => {
            this.handleSingleExport(item);
          }, 500);
        });
      }
    },
    handleSingleExport(row) {
      const params = {
        id: row.id
      };
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
    },
    handleSelectionChange(val) {
      this.selectedData = val;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customer {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
  }
}

.delete-button-container {
  flex:1;
  height: 32px;
  display: flex;
  align-items: center;
}
</style>
